<script setup>
import { ref, onMounted} from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue';
import {ElMessage} from "element-plus";
import { Plus } from '@element-plus/icons-vue'
import { addGoodsService, delGoodsService, getGoodsService, updateGoodsService } from '@/apis/goods';

const supplierForm = ref()
const dialogFormVisible = ref(false)
const form = ref({
  id: null,
  goodsId:1
})

const addOrEdit = ref('')

const supplierTableData = ref([])
const total = ref(0)
const searchInfo = ref({
  page: 1,
  pageSize: 10,
  title: '',
})
const getAllProduct = async () => {
  const res = await getGoodsService(searchInfo.value)
  console.log(res);
  supplierTableData.value = res.data.records
  total.value = res.data.total
}
const handleReset = () => {
  searchInfo.value = {}
  getAllProduct()
}
const handlePageChange = (page) => {
  console.log(page);

  searchInfo.value.page = page
  getAllProduct()
}

const del = async (id) => {
  const res = await delGoodsService(id)
  if (res.code === 200) {
    supplierTableData.value = supplierTableData.value.filter(item=> item.id !== id )
    ElMessage.success('删除成功')
  } else {
    ElMessage.error('删除失败')
  }
}


const deleteDialog = async (id) => {
  ElMessageBox.confirm(
    '是否删除？',
    '提示',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(  rs => del(id))
    .catch(err => void 0)
}
// Base64转Blob
function base64ToBlob(base64, contentType = '') {
  const sliceSize = 1024;
  const byteCharacters = atob(base64);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);
    const byteNumbers = new Array(slice.length);

    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  return new Blob(byteArrays, { type: contentType });
}
const save = async () => {
  console.log(form.value)
  const formData = new FormData()
  Object.entries(form.value).forEach(([key, value]) => {
    formData.append(key, value)
  })
  console.log(formData)
  let res
  if (addOrEdit.value === 'edit') {
    console.log(form.value);

    const blob = base64ToBlob(form.value.imageUrl, form.value.posterContentType);
    formData.append("imageFile",blob,form.value.posterContentType)
    console.log(formData);

    res = await updateGoodsService(formData)
  } else if (addOrEdit.value === 'add') {
    res = await addGoodsService(formData)
  } else {
    return false
  }

  if (res.code === 200) {
    ElMessage.success('操作成功')
    dialogFormVisible.value = false
    await getAllProduct()
  } else if (res.code === 401){
    ElMessage.error('索引无效，请检查供应商ID')
  } else {
    ElMessage.error('服务器错误')
  }
}

const add = () => {
  addOrEdit.value = 'add'
  dialogFormVisible.value = true
}

const edit = (row) => {
  addOrEdit.value = 'edit'
  form.value = row
  dialogFormVisible.value = true
}

const resetForm = () => {
  form.value = {
    id: null,
    category: "",
    posterUrl: null,
    supplierId: null,
    posterContentType: ""
  }
}



const imageUrl = ref('')



onMounted(() => {
  getAllProduct()
})
</script>

<template>
  <el-container>
    <el-header>
      <el-form>
        <el-form-item>
          <span>商品名称</span>
          <el-input v-model="searchInfo.title" style="width: 240px" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getAllProduct">
            <el-icon>
              <Search />
            </el-icon>搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>重置
          </el-button>
          <el-button @click="add">
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main v-if="supplierTableData.length !== 0">
      <el-table :data="supplierTableData" style="width: 100%"  height="auto">
        <el-table-column prop="id" label="ID">
        </el-table-column>

        <el-table-column prop="title" label="商品名称" width="160" />

        <el-table-column #default="{ row }" label="图片"  width="150">
          <img :src="`data:${row.contentType};base64,${row.imageUrl}`" width="50" height="50" alt="">
        </el-table-column>

        <el-table-column prop="price" label="价格" width="150"></el-table-column>
        <el-table-column prop="desc" label="简介" width="150"></el-table-column>
        <el-table-column prop="content" label="描述" width="150"></el-table-column>

        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteDialog(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer v-if="supplierTableData.length !== 0">
      <el-pagination background layout="prev, pager, next" :total="total" @change="handlePageChange" />
    </el-footer>
    <EmptyData v-else @reset="handleReset" />


    <el-dialog @close="resetForm" v-model="dialogFormVisible" title="Shipping address" width="500">
      <el-form ref="supplierForm" :model="form">

        <el-form-item label="商品名称">
          <el-input v-model="form.title" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.desc" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.content" clearable autocomplete="off" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="form.price" type="number" clearable autocomplete="off" />
        </el-form-item>

        <el-form-item v-if="addOrEdit==='edit'" label="图片">
          <img :src="`data:${form.contentType};base64,${form.imageUrl}`" width="50" height="50" alt="">
        </el-form-item>

        <el-form-item v-else label="图片">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :auto-upload="false"
          >
            <img v-if="imageUrl" width="60" height="60" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-container>
</template>
<style scoped lang="scss">
@import url("@/assets/style/manage.scss");
</style>
